package com.wuseguang.springcloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wuseguang.springcloud.JdbcTemplate.WXJdbc;
import com.wuseguang.springcloud.dao.jdbc.StudentsLeaveSchoolJdbc;
import com.wuseguang.springcloud.dao.repository.StudentsLeaveSchoolRepository;
import com.wuseguang.springcloud.entity.StudentsLeaveSchool;
import com.wuseguang.springcloud.service.StudentsLeaveSchoolService;
import com.wuseguang.springcloud.thread.AfterSchoolThread;
import com.wuseguang.springcloud.util.DateUtil;
import com.wuseguang.springcloud.util.Result;
import com.wuseguang.springcloud.util.WeChat.TemplateTools;
import com.wuseguang.springcloud.util.WeChat.WXUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 学生放学表 服务实现类
 * </p>
 *
 * @author
 * @since 2020-07-27
 */
@Service
public class StudentsLeaveSchoolServiceImpl implements StudentsLeaveSchoolService {


    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StudentsLeaveSchoolJdbc studentsLeaveSchoolJdbc;
    @Autowired
    private StudentsLeaveSchoolRepository studentsLeaveSchoolRepository;
    @Autowired
    private WXJdbc wXJdbc;


    @Override
    public Result findStudentsLeaveSchool(Integer classId, String findDate) {
        //查询学生放学状态
        String sql = "select s.id,s.student_name,s.head_portrait,if(sls.id is null ,0,sls.state) state," +
                "clock_in_state clockInState ,DATE_FORMAT( clock_in, '%H:%i' ) clockInDate,DATE_FORMAT(stay_after_school,'%H:%i')`lsdate` from   student s " +
                "left join students_leave_school sls on(sls.student_id=s.id and to_days(add_time) = to_days("+( StringUtils.isEmpty(findDate)?" CURDATE()":"'"+ findDate+"'")+")) where s.class_id = ? ORDER BY state    desc";
        List<Map<String, Object>> list = studentsLeaveSchoolJdbc.queryListMap(sql, classId);
        return new Result(list);
    }


    @Override
    public Result addStudentsLeaveSchool(Integer[] studentId, Integer classId, String teacherName, Integer state, String date) {

        //查询这个学生是今天是否已放学
        String sql = "select count(1) count from students_leave_school where to_days(add_time) = to_days(now()) and student_id = ?";

        for (int i = 0; i < studentId.length; i++) {

            Integer count = studentsLeaveSchoolJdbc.queryCount(sql,studentId[i]);
            //判断是否已放学
            if(count>0){
                //今天已经有放学记录不重新添加
                continue;
            }
            StudentsLeaveSchool s = new StudentsLeaveSchool();
            s.setAddTime(new Date());
            s.setClassId(classId);
            s.setStudentId(studentId[i]);
            s.setState(state);
            s.setStayAfterSchool(DateUtil.strToDateLong(date,"yyyy-MM-dd HH:mm:ss"));
            s.setClockInState(1);
            studentsLeaveSchoolRepository.save(s);

            //创建线程
            AfterSchoolThread aThread =  new AfterSchoolThread();
            aThread.setDate(date);
            aThread.setState(state);
            aThread.setTeacherName(teacherName);
            aThread.setStudentId(studentId[i]);
           //开启线程
            new Thread(aThread).start();

        }

        return new Result();
    }

    /**
     * 家长端
     * @param studentId
     * @return
     */
    @Override
    public Result findNowLeaveSchoolClockIn(Integer studentId) {
        logger.info("查询学校当天的放学打卡");
        String sql = "select id,state,DATE_FORMAT(stay_after_school,'%H:%i')`lsdate`,DATE_FORMAT(add_time,'%Y-%m-%d') `date`," +
                " DATE_FORMAT(clock_in,'%H:%i') clockInDate,clock_in_state clockInState "+
                "from students_leave_school where student_id = ? and  to_days(add_time) = to_days(now()) ";
        Map<String,Object> map = null;
        try{
            map =  studentsLeaveSchoolJdbc.queryMap(sql,studentId);
        }catch (Exception e){
            logger.info("今天没有记录");
            map = new HashMap<>();
        }
        return new Result(map);
    }

    /**
     * 家长端
     * @param studentId
     * @param findDate
     * @return
     */
    @Override
    public Result findSameMonthClockIn(Integer studentId, String findDate) {
        logger.info("查询学校当月的打卡记录");
        String sql = "select id,state,DATE_FORMAT(stay_after_school,'%H:%i')`lsdate`,DATE_FORMAT(add_time,'%Y-%m-%d') `date`, " +
                " DATE_FORMAT(clock_in,'%H:%i') clockInDate,clock_in_state clockInState "+
                "from students_leave_school where student_id = ? and  DATE_FORMAT( add_time, '%Y%m' ) = DATE_FORMAT("+( StringUtils.isEmpty(findDate)?" CURDATE() ":"'"+ findDate+"-01'")+" , '%Y%m' ) " +
                "order by  DATE_FORMAT(add_time,'%Y-%m-%d') asc";
        List<Map<String,Object>> list = studentsLeaveSchoolJdbc.queryListMap(sql,studentId);
        return new Result(list);
    }

    @Override
    public Result parentClockIn(Integer id) {
        logger.info("家长打卡");
        StudentsLeaveSchool s= studentsLeaveSchoolRepository.findById(id).get();
        s.setClockIn(new Date());
        s.setClockInState(2);
        studentsLeaveSchoolRepository.save(s);
        return new Result();
    }

    /**
     * 公众号推送
     *
     * @param studentId 教师id
     */
    public void officialAccountPush(Integer studentId,String teacherName) {

        try {
            //获取token
            String accessToken = wXJdbc.getOfficialAccountAccessToken(0);


            //查询家长的小程序openId
            String sql = "select p.open_id_one,p.id,p.open_id_two  from parent p  LEFT JOIN parent_student ps on(ps.parent_id=p.id)where ps.student_id=?";

            //家长openid
            Map<String, Object> parent = wXJdbc.queryMap(sql, studentId);
            String openId = (String) parent.get("open_id_two");

            sql = "select student_name string from student where id = ?";
            String studentName = studentsLeaveSchoolJdbc.queryString(sql,studentId);

            //判断openId是否为空
            if (!StringUtils.isEmpty(openId)) {


                Map<String, Object> pushMap = new HashMap<>();
                pushMap.put("first", "您好，尊敬的" + studentName + "家长");
                pushMap.put("keyword1", "您的孩子所在的班级，已经于"+DateUtil.time()+"放学，请您留意孩子准时到家。");
                pushMap.put("keyword2", teacherName);
                pushMap.put("keyword3", DateUtil.gettime());
                pushMap.put("remark", "请您随时关注孩子动态。");


                //跳转小程序信息
                JSONObject appletJson = new JSONObject();
                //appletJson.put("appid","wx30b606bac7775eba");
                //appletJson.put("pagepath","pages/evaluate/index");

                //解析后的数据
                JSONObject json = TemplateTools.initializationData(pushMap);
                //推送公众号信息
                WXUtil.officialAccountPush(accessToken, openId, "a9QdOrXqrfbnEPsl1-JxzVrSQhwlIU5bnTvoL8eBLhI", "", appletJson, json);
            }

        } catch (Exception e) {
            logger.error("e", e);
        }

    }


}
